Page({
  data: {
    formData: {
      name: '',
      price: '',
      description: ''
    },
    images: [],
    categories: [],
    selectedCategory: null
  },
  
  onLoad: function() {
    this.getCategories();
  },
  
  getCategories: function() {
    // 获取商品分类
    wx.request({
      url: 'https://api.example.com/categories',
      method: 'GET',
      success: (res) => {
        if (res.data.success) {
          this.setData({
            categories: res.data.categories
          });
        }
      }
    });
  },
  
  chooseImage: function() {
    wx.chooseMedia({
      count: 9 - this.data.images.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFiles = res.tempFiles;
        const tempFilePaths = tempFiles.map(file => file.tempFilePath);
        
        // 上传图片
        this.uploadImages(tempFilePaths);
      }
    });
  },
  
  uploadImages: function(filePaths) {
    wx.showLoading({
      title: '上传中...',
    });
    
    const uploads = filePaths.map(path => {
      return new Promise((resolve, reject) => {
        wx.uploadFile({
          url: 'https://api.example.com/upload',
          filePath: path,
          name: 'file',
          success: (res) => {
            const data = JSON.parse(res.data);
            if (data.success) {
              resolve(data.url);
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
    });
    
    Promise.all(uploads).then(urls => {
      wx.hideLoading();
      this.setData({
        images: [...this.data.images, ...urls]
      });
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err.message || '上传失败',
        icon: 'none'
      });
    });
  },
  
  previewImage: function(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: this.data.images,
      current: url
    });
  },
  
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.images;
    images.splice(index, 1);
    this.setData({
      images: images
    });
  },
  
  categoryChange: function(e) {
    const index = e.detail.value;
    this.setData({
      selectedCategory: this.data.categories[index]
    });
  },
  
  submitForm: function(e) {
    const formData = e.detail.value;
    
    if (!formData.name) {
      wx.showToast({
        title: '请输入商品名称',
        icon: 'none'
      });
      return;
    }
    
    if (!formData.price) {
      wx.showToast({
        title: '请输入商品价格',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.images.length === 0) {
      wx.showToast({
        title: '请上传至少一张商品图片',
        icon: 'none'
      });
      return;
    }
    
    if (!this.data.selectedCategory) {
      wx.showToast({
        title: '请选择商品分类',
        icon: 'none'
      });
      return;
    }
    
    // 提交表单
    const productData = {
      name: formData.name,
      price: parseFloat(formData.price),
      description: formData.description,
      categoryId: this.data.selectedCategory.id,
      images: this.data.images,
      status: 'active'
    };
    
    wx.showLoading({
      title: '保存中...',
    });
    
    wx.request({
      url: 'https://api.example.com/products',
      method: 'POST',
      data: productData,
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          wx.showToast({
            title: '保存成功',
            icon: 'success'
          });
          // 返回商品列表页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '保存失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },
  
  saveDraft: function() {
    const formData = this.data.formData;
    const productData = {
      name: formData.name,
      price: formData.price ? parseFloat(formData.price) : 0,
      description: formData.description,
      categoryId: this.data.selectedCategory ? this.data.selectedCategory.id : null,
      images: this.data.images,
      status: 'draft'
    };
    
    wx.showLoading({
      title: '保存中...',
    });
    
    wx.request({
      url: 'https://api.example.com/products/draft',
      method: 'POST',
      data: productData,
      success: (res) => {
        wx.hideLoading();
        if (res.data.success) {
          wx.showToast({
            title: '已保存为草稿',
            icon: 'success'
          });
          // 返回商品列表页
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.message || '保存失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  }
}); 